package com.example.apt_api

import android.app.Activity
import java.lang.Exception
import java.util.HashMap

/**
 * @author tgw
 * @date 2021/10/04
 * @describe
 */
object ButtonKnife {

    private const val SUFFIX = "$\$BindAdapterImp"

    //做了一个缓存，只有第一次bind时才通过反射创建对象
    private var mBindCache = HashMap<Any?, BindAdapter<Activity>?>()


    fun bind(target: Activity) {
        var bindAdapter: BindAdapter<Activity>? = null
        if (mBindCache[target] != null) {
            //如果缓存中有activity，从缓存中取
            bindAdapter = mBindCache[target]
        } else {
            //缓存中没有，创建一个
            try {
                val adapterClassName = target.javaClass.name + SUFFIX
                val aClass = Class.forName(adapterClassName)
                bindAdapter = aClass.newInstance() as BindAdapter<Activity>
                mBindCache[aClass] = bindAdapter
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        //调用bind
        bindAdapter?.bind(target)
    }
}